﻿using System;
using System.Collections.Generic;

namespace SharePoint.Orm {
	public abstract class ContextStackSkeleton<T> : IContextStack<T> where T : class {
		public void Push(T obj) {
			DoStackOperation(stack => stack.Push(obj));
		}

		public void Pop() {
			DoStackOperation(stack => stack.Pop());
		}

		public T GetCurrent() {
			T result = null;
			DoStackOperation(stack => {
				if (stack.Count > 0) {
					result = stack.Peek();
				}
				if (result == null) {
					result = CreateContext();
					if (result != null) {
						stack.Push(result);
					}
				}
			});
			if (result == null) {
				throw new Exception("Could not find current context item.");
			}
			return result;
		}


		protected virtual T CreateContext() {
			throw new NotImplementedException("Could not find current context item");
		}

		protected abstract void DoStackOperation(Action<Stack<T>> action);
	}
}
